package cn.it.ygh.controller;

import java.awt.image.BufferedImage;

import java.io.File;
import java.io.IOException;


import java.util.HashMap;
import java.util.Map;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import cn.it.ygh.pojo.UploadMsg;
import cn.it.ygh.utils.ConfigReader;
import cn.it.ygh.utils.FileUtil;
import cn.it.ygh.utils.Md5Util;
import cn.it.ygh.utils.UploadError;
import cn.it.ygh.utils.UploadException;



/**
 * 上传图片
 * 
 * @author ChenGR
 *
 */
@Controller
public class UploadImgController {
	/** 日志实例 */
	private static final Logger logger = Logger.getLogger(UploadImgController.class);

	@RequestMapping(value = "/upload.do")
	@ResponseBody
	public Map<Object,Object> upload(@RequestParam(value = "file", required = false) MultipartFile file,
		HttpServletRequest request, ModelMap model) {
		UploadMsg um = new UploadMsg();
		Map<Object,Object> map = new HashMap<Object, Object>();
		try {
			logger.info("---------------- upload img begin ---------------------");
			// 文件是否为空
			if (file.getSize() == 0 || file.isEmpty()) {
				throw new UploadException(UploadError.FILE_EMPTY);
			}
			// 文件是否过大
			if (file.getSize() > ConfigReader.getUpload_img_maxsize()) {
				System.out.println(file.getSize());
				System.out.println(ConfigReader.getUpload_img_maxsize());
				throw new UploadException(UploadError.FILE_TOBIG);
			}
			String path = request.getSession().getServletContext().getRealPath("/image"); 
			String path1 = request.getContextPath()+"/image/";
			//String path = FileUtil.getSavePath(ConfigReader.getUpload_img_path());
			String ori_fileName = file.getOriginalFilename();
			System.out.println(ori_fileName);
			String md5_fileName = Md5Util.getFileMD5String(file.getInputStream()) + "."
					+ FileUtil.getExtensionName(ori_fileName);
			logger.info("path:" + path);
			logger.info("ori_fileName:" + ori_fileName);
			logger.info("md5_filename:" + md5_fileName);
			
			File targetFile = new File(path, md5_fileName);

			if (!targetFile.exists()) {
				file.transferTo(targetFile);
				// 是否是图片
				if (!isImage(targetFile)) {
					targetFile.delete();
					throw new UploadException(UploadError.FILE_ERROR);
				}
			}
			um.setSuccess("true");
			um.setMsg(" upload success ");
			um.setOri_name(ori_fileName);
			um.setMd5_name(md5_fileName);
			um.setPath(path);
			map.put("path", path1+md5_fileName);
		} catch (Exception e) {
			logger.error(e);
			um.setSuccess("false");
			um.setMsg(" upload false " + e);
		}
		logger.info("---------------- upload img end ---------------------");
		

		
		return map;
	}

	/**
	 * 判断文件是否是图片
	 * @param file
	 * @return
	 * @throws IOException 
	 */
	private static boolean isImage(File file) throws IOException {
		BufferedImage bi = ImageIO.read(file);
		if(bi == null){
		   return false;
		}

		return true;
	}
	

}
